<template>
    <div class="basis-info">
        <div class="common_content">
            <Form ref="prototypeForm" :model="prototypeForm.productPlan"  :rules="prototypeFormValidate" :label-width="250">
                <Alert>
                    <h2 >基本类参数</h2>
                </Alert>
                <Row>
                    <Col span="12">
                        <FormItem label="原型编号" prop="productNumber" v-if="parentParam.op!='add'">
                            <Input v-model="prototypeForm.productPlan.productNumber" v-bind:disabled="isreadonly"
                                   class="w200"
                                   placeholder="请输入"/>
                        </FormItem>
                    </Col>
                    <Col span="12">
                        <FormItem label="原型名称" prop="productName">
                            <Input v-model="prototypeForm.productPlan.productName" v-bind:disabled="isreadonly"
                                   class="w200" type="text"  :maxlength="128"
                                   placeholder="请输入"/>
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="24">
                        <FormItem label="原型描述" prop="productDescribe">
                            <Input v-model="prototypeForm.productPlan.productDescribe" v-bind:disabled="isreadonly"
                                   class="w400"
                                   type="textarea"
                                   placeholder="请输入"/>
                        </FormItem>
                    </Col>
                </Row>
                <!-- 定价类参数-->
                <pricing-parameters ref="pricingParameters" :atomShowType="atomShowType" :parentParam="parentParam"
                                    :formDataJson="prototypeForm.json"
                                    :templateCategory="templateCategory"
                                    @repaymentChange="repaymentChange"/>
                <!--还款方式参数-->
                <repayment-method-parameters :methodParametersForm="prototypeForm.methodParametersForm"
                                             ref="repaymentMethodParameters"
                                             :repaymentMethod="repaymentMethod"
                                             @methodParametersChange="methodParametersChange"
                                             :parentParam="parentParam"/>
                <!--利率-->
                <product-plan-rate ref="productPlanRate" :parentParam="parentParam" @rateChange="rateChange"
                                   :planRatejson="prototypeForm.planRatejson"
                                   :repaymentMethod="repaymentMethod"
                                   :rateType="rateType"/>
                <!--方案选择-->
                <product-scheme-selection :productPlan="prototypeForm.productPlan"
                                          :discountType="discountType"
                                          :isRiskPricing="isRiskPricing"
                                          :isAddLoan="isAddLoan"
                                          :templateCategory="templateCategory"
                                          :parentParam="parentParam" ref="productSchemeSelection"/>
                <!--贷后参数-->
                <pricing-parameters ref="postLoan" :notAtomShowType="notAtomShowType" :parentParam="parentParam"
                                    :formDataJson="prototypeForm.postLoan"
                                    @repaymentChange="repaymentChange"/>

            </Form>
            <Alert>
                <Row style="text-align: center;">
                    <Button type="primary" icon="md-bookmark" @click="temporaryStorage" :loading="submitLoading" v-show="parentParam.status!=3">暂存</Button>
                    <Button type="primary" icon="md-bookmark" @click="save" :loading="submitLoading" v-show="parentParam.status!=3">保存</Button>
                    <Button type="primary" icon="md-backspace" :loading="submitLoading" @click="backPage">返回</Button>
                </Row>
            </Alert>
        </div>
    </div>
</template>
<script>
    import validator from '_p/afs-core-business/pages/product/common/rules.js';
    import productSchemeSelection from "./productSchemeSelection.vue";
    import pricingParameters from "./pricingParameters.vue";
    import productPlanRate from "./productPlanRate.vue";
    import repaymentMethodParameters from "./repaymentMethodParameters.vue";
    import {deepClone} from '@/libs/utils/ObjectClone'
    import circleLoading from "_c/circle-loading/circle-loading.vue";
    import {
        savePrototype,
        getPrototypeInfo,
        temporaryStorage
    } from "@/projects/afs-core-business/api/afs-product/product/productPrototype";

    export default {
        name: "product-prototype",
        components: {
            productSchemeSelection,
            pricingParameters,
            productPlanRate,
            repaymentMethodParameters,
            circleLoading
        },
        props: {
            parentParam: {
                Object,
            },
            postLoanParam: {
                Object,
            },
        },
        data() {
            return {
                rateType: null,
                isreadonly: false,
                repaymentMethod: null,
                discountType: null,
                isRiskPricing: null,
                isAddLoan: null,
                postLoan:false,
                templateCategory:null,
                submitLoading: false,
                notAtomShowType: "01",
                atomShowType: "01",
                prototypeFormValidate: {
                    productNumber: [
                        {required: true, message: "产品编号不能为空", trigger: "change"}, {validator: validator.numAndLetterValidator, trigger: "change"},
                    ],
                    productName: [
                        {required: true, message: "产品名称不能为空", trigger: "change"}
                    ],
                },
                isdisabled: true,
                prototypeForm: {
                    repaymentType: "",
                    rateType: "",
                    productPlan: {
                        extrasPlanId:'',
                        extrasPlanName:'',
                        discountPlanId:'',
                        discountPlanName:'',
                        launchPlanId:'',
                        launchPlanName:'',
                        financePlanId:'',
                        financePlanName:'',
                        riskPlanId:'',
                        riskPlanName:''
                    },
                    planRatejson: [],
                    json: {},
                    postLoan:{},
                    methodParametersForm: {
                        repaymentMethods: {
                            finalPaymentBenchmark:null,
                            finalPaymentCalculationLogic:'1',
                            intervalSelectionFinalPayment:null,
                            fromBalancePaymentInterval:null,
                            endBalancePaymentRange:null,
                            floatingProportionStepLoan:null,
                            numberStepsPerStep:null,
                            adjustedMinimumMode:null,
                            adjustedMonthlyPayments:null,
                            monthlyPaymentPercentage:null,
                            firstNMinimumLimit:null,
                            setAnyNumberCredits:null,
                            percentageTotalRepayment:null,
                            monthlySupplyAmount:null,
                            totalAmountInstalments:null
                        },
                        data: []
                    }
                }
            }
        },
        created() {
            let {status, productTemplateId} = this.parentParam;
            this.prototypeForm.productPlan.productTemplateId = productTemplateId;
            if ("3" == status) {
                this.isreadonly = true;
            }
            this.status = status;
        },
        mounted() {
            let {status, id} = this.parentParam;
            if ("1" !== status) {
                this.getInfo(id);
            }
        },
        methods: {
            getInfo(id) {
                getPrototypeInfo({id: id}).then(res => {
                    if ("0000" === res.code) {
                        this.prototypeForm.productPlan = deepClone(res.data.productPlan);
                        this.templateCategory=this.prototypeForm.productPlan.templateCategory;
                        if (res.data.methodParametersForm != null) {
                            this.prototypeForm.methodParametersForm = deepClone(res.data.methodParametersForm);
                        }
                        if (res.data.planRatejson != null) {
                            this.prototypeForm.planRatejson = deepClone(res.data.planRatejson);
                        }
                        if (!JSON.stringify(res.data.postLoan) == "{}") {
                            this.prototypeForm.postLoan = deepClone(res.data.postLoan);
                        }
                        if (res.data.json != null) {
                            this.prototypeForm.json = deepClone(res.data.json);
                        }
                    }
                })
            },
            backPage() {
                this.$emit('backPage', "退回")
            },
            temporaryStorage(){
                this.submitLoading = true;
                this.prototypeForm.json = this.$refs.pricingParameters.formData;
                this.prototypeForm.postLoan = this.$refs.postLoan.formData;
                const data = this.prototypeForm;
                temporaryStorage(data).then(res => {
                    this.submitLoading = false;
                    if (res.code === "0000") {
                        this.prototypeForm.productPlan = res.data;
                        this.$Message.success("暂存成功！");
                    }
                }).catch(() => {
                    this.submitLoading = false;
                });
            },
            save() {
                this.prototypeForm.json = this.$refs.pricingParameters.formData;
                this.prototypeForm.postLoan = this.$refs.postLoan.formData;
                const data = this.prototypeForm;
                let parms = [
                    this.$refs.pricingParameters.getForm(),
                    this.$refs.prototypeForm
                ];
                if (this.$refs.postLoan.fromDefine.length>0) {
                    parms.push(this.$refs.postLoan.getForm());
                }
                let flag1 = this.$refs['productSchemeSelection'].validateForm();
                let flag2 = this.$refs['repaymentMethodParameters'].validateForm();
                // 使用Promise.all去校验结果
                Promise.all(parms.map(this.getFormPromise)).then(res => {
                    const validateResult = res.every(item => !!item);
                    if (validateResult && flag1 && flag2) {
                        this.submitLoading = true;
                        savePrototype(data).then(res => {
                            this.submitLoading = false;
                            if (res.code === "0000") {
                                this.prototypeForm.productPlan = res.data;
                                this.$emit('backPage', "退回")
                                this.$Message.success("保存成功！");
                            }else{
                                this.$Message.error(res.msg);
                            }
                        }).catch(() => {
                            this.submitLoading = false;
                        });
                    }
                })

            },
            getFormPromise(form) {
                return new Promise(resolve => {
                    form.validate(res => {
                        resolve(res);
                    })
                })
            },
            repaymentChange(val) {
                if ("repaymentType" == val.type) {
                    this.repaymentMethod = val.value;
                    this.prototypeForm.repaymentMethod = val.value;
                } else if ("rateType" == val.type) {
                    this.rateType = val.value;
                    this.prototypeForm.rateType = val.value;
                } else if ("isAddLoan" == val.type) {
                    this.isAddLoan = val.value;
                    this.prototypeForm.isAddLoan = val.value;
                } else if ("isRiskPricing" == val.type) {
                    this.isRiskPricing = val.value;
                    this.prototypeForm.isRiskPricing = val.value;
                } else if ("discountType" == val.type) {
                    this.discountType = val.value;
                    this.prototypeForm.discountType = val.value;
                }
            },

            rateChange(val) {
                this.prototypeForm.planRatejson = val;
            },
            methodParametersChange(val) {
                this.prototypeForm.methodParametersForm=val;
            }

        }
    }
</script>
<style scoped>
    .main .btns button {
        margin-right: 10px;
    }
    .common_br {
        background-color: #f7f7f7;
        border-radius: 3px;
        border: 1px solid #dcdee2;
    }

    .common_content {
        background-color: white;
        padding: 16px;
    }
    .basis-info>>>.ivu-input[disabled]{
        color: black;
    }
    .basis-info>>>.ivu-select-disabled .ivu-select-selected-value{
        color:#515a6e;
    }
    .basis-info>>>.ivu-input-number-input[disabled]{
        color:black;
    }
</style>
